package com.ikun.common.tree;

import java.util.*;

/**
 * @ClassName TreeUtil
 * @Description:
 * @CreateDate: 2024/4/3 11:00
 */
public class TreeUtil {

    /**
     * 查找根节点 并构建树
     * @param treeNodeList
     * @return
     * @param <T>
     */
    public static <T extends TreeNode> List<T> build(List<T> treeNodeList) {
        if (Objects.isNull(treeNodeList) || treeNodeList.isEmpty()) {
            return null;
        }
        List<T> nodeList = new ArrayList<>();
        // 递归查找根节点，入口为pid == 0
        for (T t : treeNodeList) {
            if (t.getPid() == 0) {
                nodeList.add(buildChildren(t, treeNodeList));
            }
        }
        Collections.sort(nodeList, Comparator.comparingInt(TreeNode::getSort));
        return nodeList;

    }

    /**
     * 递归构建子树
     * @param treeNode 当前处理的节点
     * @param allNodes 所有节点列表
     * @return 构建好的子树节点
     */
    private static <T extends TreeNode> T buildChildren(T treeNode, List<T> allNodes) {
        for (T node : allNodes) {

            if (Objects.equals(treeNode.getId(), node.getPid())) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.getChildren().add(buildChildren(node, allNodes));
            }
            //排序
            if(Objects.nonNull(treeNode.getChildren()))
            Collections.sort(treeNode.getChildren(), Comparator.comparingInt(item -> {
                if (Objects.isNull(item.getSort())) {
                    return -1;
                } else {
                    return item.getSort();
                }
            }));
        }

        return treeNode;
    }
}
